package com.zoe.onelink.util;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.ConfigurableEnvironment;

import java.lang.management.ManagementFactory;
import java.lang.management.MemoryUsage;
import java.util.Optional;

/**
 * <p>标题: 应用程序工具类</p>
 * <p>描述: </p>
 * <p>版权: Copyright (c) 2021</p>
 * <p>公司: 智业软件股份有限公司</p>
 *
 * @version: 1.0
 * @author: ruansheng
 * @date: 2021-07-17
 */
@Slf4j
public class ApplicationUtil {

    /**
     * 打印服务器信息
     *
     * @param context 配置上下文
     */
    public static void printServerInfo(ConfigurableApplicationContext context) {
        ApplicationUtil.printServerInfo(context, true, true, true);
    }

    @Deprecated
    public static void printServerInfo(ConfigurableApplicationContext context,
                                       boolean printServerPort,
                                       boolean printDocUrl) {
        printServerInfo(context, printServerPort, printDocUrl, true);
    }

    /**
     * 打印服务器信息
     *
     * @param context         配置上下文
     * @param printServerPort 服务端口
     * @param printDocUrl     在线文档地址
     */
    public static void printServerInfo(ConfigurableApplicationContext context,
                                       boolean printServerPort,
                                       boolean printDocUrl,
                                       boolean printJVMInfo) {
        ConfigurableEnvironment environment = context.getEnvironment();
        String serverPort = Optional.ofNullable(environment.getProperty("local.server.port"))
                .orElse(environment.getProperty("server.port"));

        if (StrUtil.isBlank(serverPort)) {
            return;
        }

        if (printServerPort) {
            log.info("当前服务启动端口: {} , 项目启动耗时: {} 秒", serverPort, ManagementFactory.getRuntimeMXBean().getUptime() / 1000f);
        }
        if (printDocUrl) {
            log.info("本地接口文档地址: http://127.0.0.1:{}/doc.html", serverPort);
            String frmUrl = environment.getProperty("onelink.doc.framework-url", "http://192.168.4.89/docs/onelink-framework");
            log.info("ONE-LINK框架文档地址: {}", frmUrl);
        }
        if (printJVMInfo) {
            // 获取Java虚拟机内存管理的MXBean
            MemoryUsage heapUsage = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage();
            log.info("JVM堆内存使用情况: 初始值={}MB, 最大值={}MB, 当前值={}MB",
                    heapUsage.getInit() / 1024 / 1024,
                    heapUsage.getMax() / 1024 / 1024,
                    heapUsage.getUsed() / 1024 / 1024);
        }
    }

    public static String getLocalIpAddress() {
        try {
            return IpUtil.getLocalhost().getHostAddress();
        } catch (Exception e) {
            return "127.0.0.1";
        }
    }

}
